<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\ProductRequest;
use App\Http\Resources\ProductResource;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{

    public function index()
    {
        $products = ProductResource::collection(Product::paginate(10));
        return $products;
    }


    public function store(ProductRequest $request, Category $category, Product $product)
    {
        $category = Category::find($request->category_id);
        $category->products()->create($request->input())->save();
        return $this->message('创建成功');
    }


    public function show(Product $product)
    {
        return $product;
    }


    public function update(ProductRequest $request, Product $product)
    {
        $product->update($request->input());
        return $this->message('修改成功');
    }


    public function destroy(Product $product)
    {
        $product->delete();
        return $this->message('删除成功');
    }

    public function search(Request $request)
    {
        return Product::search($request->keyword);
    }
}
